<template>
	<view class="content">
		<!-- <menuBar menu_index="0" /> -->
		<view v-if="show_msg" class="gui-h3 gui-padding text-center gui-border-radius-large gui-bg-white gui-margin gui-margin-top-large">
			{{msg}}
			<view>
				<button v-if="!loading" size="mini" class="gui-margin-top" type="default" @click="get_data">
					刷新
				</button>
			</view>
		</view>

		<view v-else class="gui-border-radius-large"  style="margin-top: 40rpx;">
			<view class="gui-h4 gui-color-black gui-padding">工会费缴费</view>
			
			<!-- <gui-switch-navigation :items="fee_tabs" activeDirection="center" :size="0" :margin="20" padding="30rpx"
				:isCenter="true" :currentIndex="fee_Index" activeLineHeight="8rpx" :titleClass="['gui-primary-text']"
				@change="fee_change"></gui-switch-navigation> -->
			<view class="gui-flex gui-space-around" v-if="fee_tabs.length>1" style="padding: 0 30rpx;">
				<view class="fee_tab gui-ellipsis" v-for="(d,i) in fee_tabs" :class="i==fee_Index?'fee_tab_action':''"
					@click="fee_change(i)">
					{{d.name}}
				</view>
			</view>
			<view v-for="(item,index) in forms" v-if="item.feenoticeform_model"
				class="gui-border-radius-large p-20 gui-margin"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc;  background-color: rgba(255, 255, 255, 0.6);">
				<view class="gui-card-body gui-h5" style="line-height: 75rpx;">
					<view class="d-flex jc-between">
						<text class="gui-color-black popup_text">名称:</text>
						<view class="gui-color-blue flex-1 text-center border-b">
							{{item.feenoticeform_model.name||item.feenoticeform_model.note}}
						</view>
					</view>
					<view v-if="item.feeitems" class="d-flex jc-between">
						<text class="gui-color-black3 popup_text">类别:</text>
						<view class="gui-color-blue flex-1 text-center border-b">
							{{item.feeitems.name}}
						</view>
					</view>
					<view class="d-flex jc-between">
						<text class="gui-color-black popup_text">金额:</text>
						<view class="gui-color-blue flex-1 text-center border-b">
							{{item.feeamount}}
						</view>
					</view>
					<view class="d-flex jc-between" v-if="item.mch_name" style="line-height: 45rpx; padding: 10rpx 0;">
						<text class="gui-color-black popup_text" style="margin-top: 40rpx;">商户:</text>
						<view class="gui-color-blue flex-1 text-center border-b gui-h5">
							{{item.mch_name}}<br>({{item.mch_id}})
						</view>
					</view>
				</view>
			</view>
			
			<view v-if="fee_tabs[fee_Index].status!=1"  class="text-center gui-color-red gui-bold gui-margin gui-bg-white gui-padding  gui-border-radius-large gui-margin-top">
				{{fee_tabs[fee_Index].stop_msg||'缴费暂停'}}
			</view>
			
			<view v-if="fee_tabs[fee_Index].msg"  class="text-center gui-color-red gui-bold gui-margin gui-bg-white gui-padding  gui-border-radius-large gui-margin-top">
				{{fee_tabs[fee_Index].msg}}
			</view>
			
			<view v-if="fee_tabs[fee_Index].status==1" class="gui-flex gui-space-between gui-align-items-center gui-border-radius-large"
				style="margin: 0 32rpx;box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				<view v-if="sum>0" style="line-height: 80rpx;flex:1;padding: 15rpx 20rpx;">
					<text style="color: rgba(0, 0, 0, 0.8);">请选择支付方式:</text>
					<gui-radio v-if="payTypes.wx" class="pay_type" :checked="payType=='wx'" @change="payType='wx'">
						<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 10rpx 0;">
							<image mode="aspectFit" class="pay_icon" src="../../static/pay/new/wxzf.png" />微信支付
						</view>
					</gui-radio>
					<gui-radio v-if="payTypes.abcBridge" class="pay_type" :checked="payType=='abcBridge'"
						@change="payType='abcBridge'">
						<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 10rpx 0;">
							<image class="pay_icon" src="../../static/pay/new/wjf.png" />微缴费
						</view>
					</gui-radio>
					<gui-radio v-if="payTypes.app" class="pay_type" :checked="payType=='app'" @change="payType='app'">
						<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 10rpx 0;">
							<image class="pay_icon" src="../../static/pay/new/nhzy.png" />农行掌银
						</view>
					</gui-radio>
					
					<gui-radio v-if="payTypes.alipay" class="pay_type" :checked="payType=='alipay'" @change="payType='alipay'">
						<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 10rpx 0;">
							<image class="pay_icon" src="../../static/homePage/zfb.png" />支付宝
						</view>
					</gui-radio>
					<!-- <view style="line-height: 1.2rem;">
						<view>
							mch_id: {{fee_tabs[fee_Index].mch_id}}</view>
						<view>
							mch_name: {{fee_tabs[fee_Index].mch_name}}</view>
						<view>
							mch_no: {{fee_tabs[fee_Index].mch_no}}</view>
					</view> -->
				</view>
			</view>
			
			<view v-if="fee_tabs[fee_Index].status==1" class="gui-padding" >
				<button v-if="sum>0" type="default" @click="to_pay"
					class="gui-button gui-gtbg-blue gui-box-shadow gui-noborder gui-border-radius-large"
					style="height: 100rpx;">
					<text class="gui-color-white gui-button-text gui-h4" style="line-height: 100rpx">
						立即缴费 (￥{{sum}}元)</text>
				</button>
			</view>

			<!-- 历史账单查询按钮 -->
			<view class="gui-flex gui-space-between gui-align-items-center gui-padding gui-margin-top">
				<view class="gui-h4 gui-color-black">历史账单查询</view>
				<button type="default" size="mini" class="gui-bg-blue gui-color-white" @click="showHistory = !showHistory">
					{{showHistory ? '隐藏' : '查看'}}历史账单
				</button>
			</view>
			
			<!-- 历史账单查询区域 -->
			<view v-if="showHistory" class="gui-margin-bottom gui-padding gui-border-radius-large"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.8);">
				<view class="gui-h5 gui-color-black gui-margin-bottom">历史账单查询</view>
				<view class="gui-flex gui-space-between gui-align-items-center gui-margin-bottom">
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx;">开始日期:</text>
						<uni-datetime-picker start="2020-01-01" ref="ref_datePicker1" type="date" :clear-icon="false"
							v-model="historyQuery.start_date" @change="changeHistoryDate1" />
					</view>
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx">结束日期:</text>
						<uni-datetime-picker ref="ref_datePicker2" type="date" :clear-icon="false"
							v-model="historyQuery.end_date" @change="changeHistoryDate2" />
					</view>
				</view>
				<view class="gui-flex gui-space-between">
					<button type="default" size="mini" class="gui-bg-green gui-color-white" @click="getHistoryData">
						查询历史
					</button>
					<!-- <button type="default" size="mini" class="gui-bg-orange gui-color-white" @click="exportHistory">
						导出记录
					</button> -->
				</view>
				
				<!-- 历史记录显示 -->
				<view v-if="historyList.length > 0" class="gui-margin-top">
					<view class="gui-h5 gui-color-black gui-margin-bottom">工会费缴费历史（按时间倒序）</view>
					<view v-for="(item, index) in historyList" :key="'history-'+index"
						class="gui-flex gui-space-between gui-align-items-center gui-border-b gui-padding-small">
						<view style="width: 100rpx;display: flex;align-items: center;justify-content: center;">
							<image :src="getPayIcon(item.pay_type)" style="width: 40rpx;height: 40rpx;" mode="widthFix">
							</image>
						</view>
						<view class="gui-padding-small" style="flex: 1;line-height: 35rpx;">
							<view class="gui-color-black gui-h6">
								{{item.name}}(工会费)
							</view>
							<view class="gui-color-gray gui-h6">
								缴费时间: {{item.pay_time}}
							</view>
							<view class="gui-color-blue gui-h6">
								支付方式: {{getPayTypeText(item.pay_type)}}
							</view>
						</view>
						<view class="gui-padding-small" style="width: 140rpx;text-align: right;">
							<view class="gui-color-red gui-h6 gui-bold">
								￥{{item.amount}}
							</view>
							<view class="gui-color-green gui-h6 gui-padding-small gui-border-radius-small status-text">
								缴费成功
							</view>
						</view>
					</view>
				</view>
				<view v-else-if="historySearched && historyList.length === 0" class="gui-text-center gui-color-gray gui-margin-top">
					暂无历史记录
				</view>
				<!-- 调试信息 -->
				
			</view>

		</view>

	</view>
</template>

<script>
	import menuBar from "./menu_bar"
	export default {
		components: {
			menuBar
		},
		data() {
			return {
				
				fee_tabs: [],
				fee_list: [],
				fee_name: "",
				payTypes: {
					wx: false,
					app: false,
					abcBridge: false,
					alipay:false,
				},
				fee_Index: 0,

				content: '工会费缴费说明',
				forms: [],
				list: [],
				payType: null,
				blance: 0,
				sum: 0,
				show_msg: true,
				msg: '查询账单中..',
				loading: false,
				
				// 历史账单查询相关
				showHistory: false,
				historyList: [],
				historySearched: false,
				historyQuery: {
					start_date: '',
					end_date: ''
				}
				
			}
		},
		onShow() {
			this.forms=[];
			this.list=[];
			this.sum=0;
			this.fee_Index=0;
			this.fee_tabs= [];
			this.fee_list= [];
			
			// 初始化历史查询日期
			const today = new Date();
			const year = today.getFullYear();
			const month = today.getMonth() + 1;
			const day = today.getDate();
			this.historyQuery.start_date = `${year}-01-01`;
			this.historyQuery.end_date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			
			this.get_data();
		},
		onNavigationBarButtonTap(e) {
			uni.navigateTo({
				url: "/pages/pay/pay_index"
			})
		},
		methods: {
			fee_change(n) {
				//切换
				console.log(n);
				this.fee_Index = n;
				this.forms = this.list[this.fee_tabs[n].id];

				console.log("this.fee_tabs", this.fee_tabs);
				console.log(this.forms);
				this.fee_name = this.fee_tabs[n].name;
				this.sum = 0;
				let self = this;
				this.forms.map(d => {
					if (d.feenoticeform_model) {
						this.sum += parseFloat(d.feeamount) * 100;
					}

					d.mch_name = self.fee_tabs[n].mch_name;
					d.mch_id = self.fee_tabs[n].mch_id;
					d.mch_no = self.fee_tabs[n].mch_no;
				})
				this.sum = Math.round(this.sum) / 100;
				console.log(this.sum);
				console.log('数据forms: ', this.forms);
				let ps = this.fee_tabs[n].pay_types
				this.payTypes.wx = false;
				this.payTypes.app = false;
				this.payTypes.abcBridge = false;
				this.payTypes.alipay=false;
				for (let i = 0; i < ps.length; i++) {
					if (ps[i] == "微信直缴") {
						this.payTypes.wx = true;
					} else if (ps[i] == "农行支付") {
						this.payTypes.app = true;
					} else if (ps[i] == "微缴费") {
						this.payTypes.abcBridge = true;
					}else if (ps[i]=='支付宝'){
						this.payTypes.alipay = true;
					}
				}
			},
			get_data() {
				console.log("ghf->get_data");
				let self = this;
				if (this.loading) return;
				this.loading = true;
				this.msg = "查询账单中.";
				this.show_msg = true;
				this.sum = 0;
				this.payType = null;
				this.payTypes.wx = false;
				this.payTypes.app = false;
				this.fee_tabs = [];
				this.payTypes.abcBridge = false;
				this.$boya.NPost("/app/fee/query", {
					type: 0
				}, function(res) {
					console.log("app/fee/query", res);
					self.loading = false;
					if (res.data.hasOwnProperty("list")) {
						if (Object.keys(res.data.list).length > 0) {
							self.show_msg = false;
							self.msg = "";
							self.list = res.data.list;

							let _keys = Object.keys(res.data.list);
							self.forms = res.data.list[_keys[0]];
							self.sum = res.data.sum;
							self.blance = res.data.blance;
							self.fee_list = res.data.fee_items;
							self.fee_name = self.fee_list[0].name;
							
							res.data.fee_items.map(d => {
								self.fee_tabs.push({
									id: d.id,
									name: d.name,
									pay_types: d.pay_types,
									app_id: d.app_id ?? null,
									app_path: d.app_path ?? null,
									mch_id: d.mch_id ?? null,
									mch_name: d.mch_name ?? null,
									mch_no: d.mch_no ?? null,
									status:d.status??0,
									msg:d.msg,
									stop_msg:d.stop_msg
								});
							})
							console.log("fee_tabs", self.fee_tabs);
							setTimeout(function() {
								self.fee_change(0);
							}, 200);
							console.log('this.sum: ', self.sum);
						} else {
							self.show_msg = true;
							self.msg = "暂时没有缴费账单!";
						}
					} else {
						self.show_msg = true;
						self.msg = "暂时没有缴费账单!";
					}
				}, function(err) {
					console.log(err);
					self.loading = false;
				}, {
					showLoading: false
				})
			},
			to_pay() {
				let ids = [];
				if (!this.payType) {
					uni.showToast({
						title: "请选择支付类型",
						icon: 'error'
					})
					return;
				}
				for (let i = 0; i < this.forms.length; i++) {
					ids.push(this.forms[i].id);
				}

				uni.showToast({
					title: "创建订单"
				})
				let self = this;
				let parm = {
					ids: ids.join(","),
					pay_type: this.payType,
					pay_amount: this.sum,
					fee_id: this.fee_tabs[this.fee_Index].id
				}

				console.log(this.fee_tabs[this.fee_Index]);

				console.log("to_pay->创建订单", JSON.stringify(parm));
				self.loading = true
				this.$boya.NPost("/app/fee/create_order",
					parm,
					function(res) {
						console.log(res);
						uni.showToast({
							title: "发起支付"
						})
						self.loading = false;
						console.log("支付方式：", self.payType);
						let app_id = self.fee_tabs[self.fee_Index].app_id
						let app_path = self.fee_tabs[self.fee_Index].app_path
						//通过微信小程序支付或微缴费
						res.type = self.payType;
						res.data.type = self.payType;
						res.data.app_id = self.fee_tabs[self.fee_Index].app_id;
						res.data.app_path = self.fee_tabs[self.fee_Index].app_path;

						if (self.payType == 'abcBridge') {
							//农行微缴费
							res.data.app_id = "gh_a6986a2f785e";
							let user=uni.getStorageSync("userInfo");
							let path = "page/containers/payment/query-input/query-input?code=" + res.data
								.code;							
							path=path+"&userInput="+encodeURIComponent(JSON.stringify({input1:user.id_no,input2:user.real_name}));
							res.data.app_path=path;
						}

						console.log("create_order", JSON.stringify(res));

						
						uni.navigateTo({
							url: "/pages/pay/pay_info?data=" + encodeURIComponent(JSON.stringify(res)),
							fail(err) {
								console.log(err);
							}
						})
						
					},
					function(err) {
						console.log("create_order->error", JSON.stringify(err));
						let content = err.msg;
						if (err.data.length > 0) {
							content += ",订单号:" + err.data[0].order_no;
						}
						uni.showModal({
							title: "订单异常",
							content: content,
							showCancel: false

						})
						self.loading = false;
					}
				)

			},
			
			// 历史账单查询相关方法
			changeHistoryDate1(e) {
				this.historyQuery.start_date = e;
				this.$refs.ref_datePicker1.close();
			},
			changeHistoryDate2(e) {
				this.historyQuery.end_date = e;
				this.$refs.ref_datePicker2.close();
			},
			getHistoryData() {
				let self = this;
				let parm = {
					"page": 1,
					"limit": 50,
					"type": "feenoticeform"
					// 暂时不添加status过滤，看看原始数据
				};
				
				if (this.historyQuery.start_date != '') {
					parm.start_date = this.historyQuery.start_date;
				}
				if (this.historyQuery.end_date != '') {
					parm.end_date = this.historyQuery.end_date;
				}
				
				console.log('查询参数:', parm);
				
				uni.showLoading({
					title: '查询中...'
				});
				
				this.$boya.NGet("/app/pay/order_list", parm, function(res) {
					console.log('工会费历史记录: ', res);
					uni.hideLoading();
					self.historySearched = true;
					
					if (res.data && Array.isArray(res.data)) {
						console.log('原始数据长度:', res.data.length);
						console.log('过滤前数据:', res.data);
						
						// 先不过滤状态，看看所有数据
						self.historyList = res.data
							.sort((a, b) => new Date(b.pay_time) - new Date(a.pay_time));
						
						console.log('排序后数据长度:', self.historyList.length);
						console.log('排序后数据:', self.historyList);
						
						// 处理支付状态显示
						self.historyList.forEach(item => {
							item.pay_status_text = self.getPayStatusText(item.pay_status);
							item.pay_type_text = self.getPayTypeText(item.pay_type);
						});
					} else {
						console.log('数据格式不正确:', res.data);
						self.historyList = [];
					}
				}, function(err) {
					console.log('获取工会费历史记录失败: ', err);
					uni.hideLoading();
					self.historySearched = true;
					self.historyList = [];
					uni.showToast({
						title: '查询失败',
						icon: 'error'
					});
				});
			},
			exportHistory() {
				if (this.historyList.length === 0) {
					uni.showToast({
						title: '暂无数据可导出',
						icon: 'none'
					});
					return;
				}
				
				// 导出功能实现
				let exportData = this.historyList.map(item => ({
					缴费时间: item.pay_time,
					缴费金额: `￥${item.amount}`,
					支付方式: this.getPayTypeText(item.pay_type),
					缴费状态: '缴费成功'
				}));
				
				// 这里可以调用导出API或生成文件
				console.log('导出数据:', exportData);
				uni.showToast({
					title: '导出功能开发中',
					icon: 'none'
				});
			},
			getPayIcon(payType) {
				switch (payType) {
					case 'wx':
						return '../../static/homePage/wx.png';
					case 'abcBridge':
						return '../../static/homePage/xcx.png';
					case 'OPEN':
						return '../../static/homePage/xcx.png';
					case 'app':
						return '../../static/homePage/nh.png';
					default:
						return '../../static/homePage/wx.png';
				}
			},
			getPayTypeText(payType) {
				switch (payType) {
					case 'wx':
						return '微信支付';
					case 'abcBridge':
						return '微缴费';
					case 'OPEN':
						return '微缴费';
					case 'app':
						return '农行掌银';
					default:
						return '未知方式';
				}
			},
			getPayStatusText(status) {
				switch(Number(status)) {
					case 1:
						return '缴费成功';
					case 0:
						return '处理中';
					case -1:
						return '缴费失败';
					default:
						return '未知状态';
				}
			}

		}
	}
</script>

<style>
	.content {
		width: 100vw;
		height: 100vh;
		background: url('../../static/pay/new/bj1.png') 100% 100% / 100% 100%;
	}
	
	.pay_type {
		display: flex;
		align-items: center;
		gap: 20rpx;
		font-size: 1.2rem;
		/* border-bottom: 1rpx solid #ccc; */
		padding: 10rpx 0;
		line-height: 50rpx;
		font-size: 32rpx;

		image {
			width: 60rpx;
			height: 60rpx;
			margin-right: 20rpx;
		}

		.gui-radio-lable {
			display: flex;
			align-items: center;
		}
	}

	.pay_icon {
		width: 30px;
		height: 30px;
	}
	
	.status-text {
		white-space: nowrap;
		font-size: 24rpx;
	}

	.fee_tab {
		padding: 5rpx;
		color: #333333;
	}

	.fee_tab_action {
		color: #2742bf;
		font-weight: bold;
		border-bottom: solid 1rpx #2742bf;
	}
</style>